package com.example.springbooksystem.interceptor;

import com.example.springbooksystem.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-01-29
 * @time: 15:09:22
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始执行登录拦截校验...");
        HttpSession session = request.getSession(false);
        if (session != null
                && session.getAttribute(Constants.SESSION_USER_KEY) != null) {
            log.info("身份认证成功, 放行");
            return true;
        }
        response.setStatus(401);
        log.info("身份认证失败, 拦截");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        log.info("目标方法执行后, 反馈执行");
    }

}
